<?php

namespace App\Listeners;

use App\Events\GameFinish;
use App\Models\ChildStar;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class ChangeTop
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  GameFinish  $event
     * @return void
     */
    public function handle(GameFinish $event)
    {
        $tmp = $event->history;

        $last = ChildStar::where(['child_id'=>$tmp->child_id, 'code'=>$tmp->game->code])->first();

        $data = ['child_id'=>$tmp->child_id,
            'history_id'=>$tmp->id,
            'last_history_id'=>$tmp->id,
            'code'=>$tmp->game->code,
            'category_id'=>$tmp->category_id,
            'grade_id'=>$tmp->grade_id,
            'star'=>$tmp->end_star,
            'last_star'=>$tmp->end_star,
            'top_star_time'=>$tmp->end_time,
            'last_star_time'=>$tmp->end_time
        ];

        if (empty($last)){
            //Log::error($data);
            if (!ChildStar::create($data)){
                Log::error("child top star insert error");
            }
        }else{
            if ($last->star >= $tmp->end_star){
                //添加最新训练，
                $data=[
                    'last_history_id'=>$tmp->id,
                    'last_star'=>$tmp->end_star,
                    'last_star_time'=>$tmp->end_time
                    ];
            }

            if ( !$last->update($data) ){
                Log::error("child top star update error");
            }
        }
    }
}
